package com.study.manage.mvc.org.brand;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.BrandOrgShopRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.BrandOrgShop;
import com.study.manage.domain.User;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.SessionUser;
import com.study.manage.mvc.common.BaseController;
import com.study.manage.utils.MapUtils;

@Controller
@RequestMapping("org/acc")
@Scope("request")
public class BrandOrganizationController extends BaseController {

	@Autowired
    private UserRepository userRepository;

    @Autowired
    private BrandOrgShopRepository brandOrgShopRepository;

    @RequestMapping(path = "brand", method = RequestMethod.GET)
    public String brand(ModelMap model) {
    	
    	SessionUser su = (SessionUser) session.getAttribute("user");
        User user = userRepository.findOne(su.getId());
        BrandOrgShop bos = brandOrgShopRepository.findByUserIdAndState(su.getId(), LiveDieState.LIVE);
        if(bos==null) {
        	bos = new BrandOrgShop();
        }
        Map<String, Object> map = MapUtils.convert(bos);
        map.put("isBrandOrg", user.isBrandOrg);
        model.put("data", map);
        return "org/acc/brand";
    }

    @ResponseBody
    @RequestMapping(path = "brand-save", method = RequestMethod.POST)
    public AjaxResponse brand_save(BrandOrganizationForm form , ModelMap model) throws Exception {
    	
    	AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = (SessionUser) session.getAttribute("user");
        BrandOrgShop bos = brandOrgShopRepository.findByUserIdAndState(su.getId(), LiveDieState.LIVE);
        if (bos == null) {
            bos = new BrandOrgShop();
            bos.userId = su.getId();
        }
        bos.title = form.getTitle();
        bos.url = form.getUrl();
        bos.pic = form.getPic();
        bos.description = form.getDescription();
        brandOrgShopRepository.save(bos);
        return ajax;
    }
}
